import {Component} from 'react';
import React from 'react';
import {connect} from 'umi';

// import HighPerformTable from '@/components/HighPerformTable';
import HighPerformTable from '@/components/HighPerformTableSpecially';
import {Button, Select} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import APIS from '@/apis';
import SearchAbleSelect from '@/components/SearchAbleSelect';
import CustomCascader from '@/components/CustomCascader/CustomCascader';
import {values} from 'lodash';
import {message} from '@umijs/plugin-request/lib/ui';

// const Option = Select.Option;

class MajorManagerPage extends Component<any, any> {
  actionRef: any;

  search: SearchAbleSelect | undefined;

  constructor(props: any) {
    super(props);
    this.state = {
      schoolId: 0,
      filterSchoolId: 0,
      filterMajorId: -1,
      currentId: -1,
    }
  }

  componentDidMount() {
    APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 100}).then((res) => {
      // this.schoolId=res[0].id;
      // this.setState({schoolId:res[0].id})
    })
  }

  handleDelete(data: any) {
    return APIS.OrgsAPI.DeleteMajor(data.id)
      .then(() => {
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.resolve(false);
      });
  }

  // filterSchoolId:0,
  //     filterMajorId:-1,

  handleAdd(data: any) {

    if (data.college !== undefined && data.school !== undefined && data.majorName !== undefined) {
      return APIS.OrgsAPI.CreateNewMajor(data)
        .then(() => {
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.resolve(false);
        });
    } else if (this.state.filterSchoolId !== 0 && this.state.filterMajorId !== -1 && data.majorName) {
      data.school = this.state.filterSchoolId;
      data.college = this.state.filterMajorId

      return APIS.OrgsAPI.CreateNewMajor(data)
        .then(() => {
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.resolve(false);
        });

    } else {
      message.error({
        content: '请填写全部数据',
      })
      return Promise.resolve(false);
    }


  }


  private filterId?: any = -1;
  private schoolId?: any = -1;

  handleChangeFilter(values: any) {
    if (values[0]) {
      //学校
      this.schoolId = values[0];
      if (!values[1]) {
        this.filterId = -1;
      }
      this.actionRef.reload();
    }
    if (values[1]) {
      //院系
      this.filterId = values[1];
      this.actionRef.reload();
    }

  }

  handleUpdate(data: any) {

    if (data.collage !== undefined && data.school !== undefined && data.majorName !== undefined) {
      return APIS.OrgsAPI.UpdateMajor(data)
        .then(() => {
          return Promise.resolve(true);
        })
        .catch(() => {
          return Promise.resolve(false);
        });
    } else {
      message.error({
        content: '请填写全部数据',
      })
      return Promise.resolve(false);
    }
  }

  requestGetData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    return APIS.OrgsAPI.GetMajorList({...params, sorter, filter, college: this.filterId, school: this.schoolId});
  }

  clomns: any = [
    {
      title: '专业名称',
      dataIndex: 'majorName',
      rules: [
        {
          required: true,
          message: '规则名称为必填项',
        },
      ],
    },
    {
      title: '学校',
      dataIndex: 'school',
      hideColumn: true,
      rules: [
        {
          required: true,
          message: '规则名称为必填项',
        },
      ],
      renderFormItem: (item: any, config: any, form: any) => (
        <SearchAbleSelect
          searchData={async (key) => {
            var datas: Array<any> = await APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 9999});
            return Promise.resolve(
              datas.map((item) => {
                return {value: item.id, key: item.name};
              }),
            );
          }}
          initialValue={this.state.currentId === -1 ? this.state.filterSchoolId : this.state.currentId}
          // values={this.state.currentId === -1 ? this.state.filterSchoolId : this.state.currentId}
          form={form}
          name="school"
          placeholder='请选择一个学校'
          getValue={(value) => {
            this.setState({schoolId: value.school})
            setTimeout(() => {
              this.search?.onSearch('');
            }, 100);
          }}
        />
      ),
    },
    {
      title: '学院',
      dataIndex: 'college',
      rules: [
        {
          required: true,
          message: '学院为必填项',
        },
      ],
      renderText: (dataIndex: any, record: any) => <span>{record.collegeData?.collegeName}</span>,
      renderFormItem: (item: any, config: any, form: any) => (
        <SearchAbleSelect
          ref={(ref: any) => this.search = ref}
          searchData={async (key) => {
            // console.log(this.state.schoolId)
            var datas: Array<any> = await APIS.OrgsAPI.SearchGetCollegeList({id: this.state.schoolId});
            if (datas === undefined) {
              datas = new Array<any>();
            }
            return Promise.resolve(
              datas.map((item) => {
                return {value: item.id, key: item.collegeName};
              }),
            );
          }}
          initialValue={this.state.filterMajorId === -1 ? form.getFieldValue("collegeData")?.collegeName : this.state.filterMajorId}
          // values={this.state.filterMajorId===-1?form.getFieldValue("collegeData")?.collegeName:this.state.filterMajorId}
          // initialValue={form.getFieldValue("collegeData")?.collegeName}
          form={form}
          name="college"
          placeholder='请选择一个学院'
        />
      ),
    },
    {
      title: '更新时间',
      hideInForm: true,
      dataIndex: 'updatedTime',
      // valueType: 'datatime',
    },
  ];

  handleChangeSchoolAndMajor(data: any) {

    // console.log(data);
    this.setState({
      filterSchoolId: data[0] ? data[0] : 0,
      schoolId: data[0] ? data[0] : 0,
      filterMajorId: data[1] ? data[1] : -1,
    })
  }


  handleChangeState(record: any, state: boolean) {
    return APIS.OrgsAPI.ChangeMajorState({id: record.id, state: state ? 1 : 0}).then(
      (response) => {
        return Promise.resolve(response.data.state === 1);
      },
    );
  }

  render() {
    return (
      <div>
        <CustomCascader datasource={[{
          placeholder: "请选择学校",
          dataGet: (values) => APIS.OrgsAPI.SearchGetSchoolList({current: 1, pageSize: 100}), renderOption: (data) => {
            return <Select.Option key={data.id} value={data.id}>{data.name}</Select.Option>
          }
        }, {
          placeholder: "请选择院系",
          dataGet: (values) => APIS.OrgsAPI.GetCollegeListBySchool({
            current: 1,
            pageSize: 100,
            id: values[0]
          }).then((res) => res.data), renderOption: (data) => {
            return <Select.Option key={data.id} value={data.id}>{data.collegeName}</Select.Option>
          }
        }]} onChange={(values) => {
          this.handleChangeFilter(values)
          this.handleChangeSchoolAndMajor(values);

        }}/>
        <HighPerformTable<any>
          requestGetData={this.requestGetData.bind(this)}
          ref={(ref) => (this.actionRef = ref)}
          columns={this.clomns}
          handleDelete={this.handleDelete.bind(this)}
          handleAdd={this.handleAdd.bind(this)}
          handleChangeState={this.handleChangeState.bind(this)}
          handleUpdate={this.handleUpdate.bind(this)}
          onClickUpdate={record => {

            // console.log(record)
            this.setState({currentId: record.collegeData.schoolInfo.id})
            this.actionRef.handleUpdateModalVisible(true, record)
          }}
          toolBarRender={() => [
            <Button type="primary" onClick={() => {
              this.setState({currentId: -1});
              this.actionRef.handleModalVisible(true)
            }}>
              <PlusOutlined/> 新增专业
            </Button>,
          ]}
        />
      </div>
    );
  }
}

export default connect()(MajorManagerPage);
